package cn.le.workQueues;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 项目名  spring-boot
 * Created by lansp
 * Created at 2018/5/31
 * 描述:
 */
@Configuration
public class NoeRabbitConfig {

	@Bean
	public Queue queue(){
		return new Queue("rtu-status-queue-dev");
	}

	/*
		高并发中的消息生产和消费,会产生一个问题, 万一客户端在处理消息的时候挂了,那么这条消息就相当于被浪费了,针对这种情况,rabbitmq
		推出了ack机制,和tcp三次握手类型

		spring-boot实现ack

		test默认下 消息还未读取完,项目就会停止,在正式线上环境不会出现这种情况,  在测试的方法主线程暂停也可以放消息有足够的时候读取完
	 */
	@Autowired
	private ConnectionFactory connectionFactory;
	@Bean
	public SimpleMessageListenerContainer messageListenerContainer(){
		SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
		container.setQueues(queue());
		container.setExposeListenerChannel(true);
		container.setMaxConcurrentConsumers(1);
		container.setConcurrentConsumers(1);
		container.setAcknowledgeMode(AcknowledgeMode.MANUAL);//消息确认后才能删除
		container.setPrefetchCount(5);//每次处理5条数据
		container.setMessageListener(new ChannelAwareMessageListener() {
			@Override
			public void onMessage(Message message, Channel channel) throws Exception {
				byte[] body = message.getBody();
				System.out.println("消息端接收到消息:" + new String (body));
				channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
			}
		});
		return container;
	}

}














